<template>
  <div>
    <TaskChatDialog
      :model-value="modelValue"
      title="添加"
      width="40%"
      class="quality-dialog"
      body-class-name="dialog-quality"
      append-to-body
      @close="close"
      destroy-on-close>
      <el-form ref="formRef" :model="form" label-width="120px" :rules="formRules">
        <el-form-item label="名称：" prop="name">
          <el-input v-model="form.name" placeholder="请输入名称" />
        </el-form-item>
        <el-form-item label="图标：" prop="icon">
          <el-popover placement="bottom-start" trigger="click" width="600">
            <div class="modal-box">
              <IconSelect ref="iconSelect" @selected="selected" />
            </div>
            <template #reference>
              <el-button type="primary" link class="group-img" v-if="!form.icon">选择图标</el-button>
              <div v-else>
                <SvgIcon :name="form.icon" :color="form.deskColor" size="16"></SvgIcon>
                <span class="icon-name">{{ form.icon }}</span>
              </div>
            </template>
          </el-popover>
        </el-form-item>
        <el-form-item label="URL：" prop="url">
          <el-input v-model="form.url" placeholder="请输入URL" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="close">取 消</el-button>
          <el-button type="primary" :loading="loading" @click="submit">保存</el-button>
        </span>
      </template>
    </TaskChatDialog>
  </div>
</template>

<script setup>
import { ElMessage } from 'element-plus'

const props = defineProps({
  modelValue: Boolean,
})

const emit = defineEmits(['update:modelValue', 'refresh'])

const loading = ref(false)

const form = ref({
  name: '',
  icon: '',
  url: 'https://webpack.js.org/',
})
const formRef = ref()

let formRules = {
  name: [{ required: true, message: '请输入名称', trigger: 'blur' }],
  url: [{ required: true, message: '请输入URL', trigger: 'blur' }],
}

// 选择分组图标
function selected(name) {
  form.value.icon = name
}

function submit() {
  formRef.value.validate(async (valid) => {
    if (valid) {
      loading.value = true
      setTimeout(() => {
        ElMessage.success('提交成功')
        loading.value = false
        emit('refresh', JSON.parse(JSON.stringify(form.value)))
        close()
      }, 1000)
    }
  })
}
function close() {
  formRef.value.resetFields()
  emit('update:modelValue', false)
}
</script>

<style lang="scss" scoped>
.group-img {
  margin-left: 5px;
  cursor: pointer;
}
.icon-name {
  position: relative;
  top: -3px;
  margin-left: 5px;
}
</style>
